/*
 * -\-\-
 * Mobius
 * --
 * Copyright (c) 2017-2020 Spotify AB
 * --
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * -/-/-
 */

package com.spotify.mobius.ohos;

import static com.spotify.mobius.internal_util.Preconditions.checkNotNull;

import com.spotify.mobius.First;
import com.spotify.mobius.MobiusLoop;
import com.spotify.mobius.Next;

import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

/**
 * OhosLogger<M, E, F>
 *
 * @param <M> m
 * @param <E> e
 * @param <F> f
 */
public class OhosLogger<M, E, F> implements MobiusLoop.Logger<M, E, F> {
    private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x00201, "MY_TAG");

    private final String tag;

    /**
     * OhosLogger
     *
     * @param tag tag
     * @param <M> m
     * @param <E> e
     * @param <F> f
     * @return
     */
    public static <M, E, F> OhosLogger<M, E, F> tag(String tag) {
        return new OhosLogger<>(tag);
    }

    public OhosLogger(String tag) {
        this.tag = checkNotNull(tag);
    }

    @Override
    public void beforeInit(M model) {
        HiLog.debug(LABEL, tag + " Initializing loop");
    }

    @Override
    public void afterInit(M model, First<M, F> result) {
        HiLog.debug(LABEL, tag + " Loop initialized, starting from model: " + result.model());

        for (F effect : result.effects()) {
            HiLog.debug(LABEL, tag + " Effect dispatched: " + effect);
        }
    }

    @Override
    public void exceptionDuringInit(M model, Throwable exception) {
        HiLog.debug(LABEL, tag + " FATAL ERROR: exception during initialization from model '" + model + "'", exception);
    }

    @Override
    public void beforeUpdate(M model, E event) {
        HiLog.debug(LABEL, tag + " Event received: " + event);
    }

    @Override
    public void afterUpdate(M model, E event, Next<M, F> result) {
        if (result.hasModel()) {
            HiLog.debug(LABEL, tag + " Model updated: " + result.modelUnsafe());
        }

        for (F effect : result.effects()) {
            HiLog.debug(LABEL, tag + " Effect dispatched: " + effect);
        }
    }

    @Override
    public void exceptionDuringUpdate(M model, E event, Throwable exception) {
        HiLog.debug(LABEL, tag +
                String.format(" FATAL ERROR: exception updating model '%s' with event '%s'", model, event),
            exception);
    }
}
